package io.renren.system.sys.controller;

import io.renren.common.annotation.LogOperation;
import io.renren.common.exception.ErrorCode;
import io.renren.common.export.ExcelUtils;
import io.renren.common.page.PageData;
import io.renren.common.utils.ConvertUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.system.security.password.PasswordUtils;
import io.renren.system.security.user.SecurityUser;
import io.renren.system.security.user.UserDetail;
import io.renren.system.sys.dto.PasswordDTO;
import io.renren.system.sys.dto.SysUserDTO;
import io.renren.system.sys.enums.SuperAdminEnum;
import io.renren.system.sys.enums.UserStatusEnum;
import io.renren.system.sys.excel.SysUserExcel;
import io.renren.system.sys.service.SysRoleUserService;
import io.renren.system.sys.service.SysUserService;
import io.renren.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys/user")
@Api(tags = "系统设置-用户管理")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleUserService sysRoleUserService;

    @GetMapping("page")
    @ApiOperation("根据查询条件分页获取用户列表")
    @RequiresPermissions("sys:user:page")
    public Result<PageData<SysUserDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
        PageData<SysUserDTO> page = sysUserService.page(params);
        return new Result<PageData<SysUserDTO>>().ok(page);
    }

    @GetMapping("export")
    @ApiOperation("根据查询条件获取并导出用户列表")
    @LogOperation("根据查询条件获取并导出用户列表")
    @RequiresPermissions("sys:user:export")
    @ApiImplicitParam(name = "username", value = "用户名", paramType = "query", dataType = "String")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<SysUserDTO> list = sysUserService.list(params);
        ExcelUtils.exportExcelToTarget(response, null, list, SysUserExcel.class);
    }

    @GetMapping("{id}")
    @ApiOperation("根据用户编号获取用户详细信息")
    @RequiresPermissions("sys:user:info")
    public Result<SysUserDTO> get(@PathVariable("id") Long id) {
        SysUserDTO data = sysUserService.get(id);
        //用户角色列表
        List<Long> roleIdList = sysRoleUserService.getRoleIdList(id);
        data.setRoleIdList(roleIdList);
        return new Result<SysUserDTO>().ok(data);
    }

    @PutMapping("password")
    @ApiOperation("修改密码")
    @LogOperation("修改密码")
    public Result password(@RequestBody PasswordDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto);
        UserDetail user = SecurityUser.getUser();
        //原密码不正确
        if (!PasswordUtils.matches(dto.getPassword(), user.getPassword())) {
            return new Result().error(ErrorCode.PASSWORD_ERROR);
        }
        sysUserService.updatePassword(user.getId(), dto.getNewPassword());
        sysUserService.clearLogin(user.getId());// 清除指定用户登录状态
        return new Result();
    }

    @PostMapping
    @ApiOperation("新增保存用户信息")
    @LogOperation("新增保存用户信息")
    @RequiresPermissions("sys:user:save")
    public Result save(@RequestBody SysUserDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        SysUserDTO dtoDB = sysUserService.getByUsername(dto.getUsername());
        if (StringUtils.isNotEmpty(dtoDB)) {//表示用户名已存在，此时不能新增用户
            return new Result().error("用户名已存在!");
        }
        sysUserService.save(dto);
        return new Result();
    }

    @PutMapping
    @ApiOperation("修改保存用户信息")
    @LogOperation("修改保存用户信息")
    @RequiresPermissions("sys:user:update")
    public Result update(@RequestBody SysUserDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        SysUserDTO dtoDB = sysUserService.get(dto.getId());
        if (StringUtils.isEmpty(dtoDB)) {
            return new Result().error("用户不存在!");
        }
        sysUserService.update(dto, true);
        return new Result();
    }

    @DeleteMapping("{id}")
    @ApiOperation("根据用户编号删除用户信息")
    @LogOperation("根据用户编号删除用户信息")
    @RequiresPermissions("sys:user:delete")
    public Result delete(@PathVariable("id") Long id) {
        UserDetail user = SecurityUser.getUser();
        if (user.getSuperAdmin() == SuperAdminEnum.NO.value()) {//非超级管理员
            return new Result().error("无权删除用户，请联系超级管理员!");
        }
        //效验数据
        AssertUtils.isNull(id, "id");
        sysUserService.deleteById(id);
        sysUserService.clearLogin(id);// 清除指定用户登录状态
        return new Result();
    }

    @GetMapping("info")
    @ApiOperation("获取登录用户信息")
    public Result<SysUserDTO> info() {
        SysUserDTO data = ConvertUtils.sourceToTarget(SecurityUser.getUser(), SysUserDTO.class);
        return new Result<SysUserDTO>().ok(data);
    }

    @GetMapping("lockuser/{id}")
    @ApiOperation("锁定用户")
    //@RequiresPermissions("sys:user:lockuser")
    public Result<SysUserDTO> lockuser(@PathVariable("id") Long id) {
        SysUserDTO dtoDB = sysUserService.get(id);
        if (StringUtils.isEmpty(dtoDB)) {
            return new Result().error("用户不存在!");
        }
        dtoDB.setStatus(UserStatusEnum.DISABLE.value());
        sysUserService.update(dtoDB, false);
        sysUserService.clearLogin(id);// 清除指定用户登录状态
        return new Result();
    }

    @GetMapping("unlockuser/{id}")
    @ApiOperation("解锁用户")
    //@RequiresPermissions("sys:user:unlockuser")
    public Result<SysUserDTO> unlockuser(@PathVariable("id") Long id) {
        SysUserDTO dtoDB = sysUserService.get(id);
        if (StringUtils.isEmpty(dtoDB)) {
            return new Result().error("用户不存在!");
        }
        dtoDB.setStatus(UserStatusEnum.ENABLED.value());
        sysUserService.update(dtoDB, false);
        return new Result();
    }

    @GetMapping("resetPwd/{id}")
    @ApiOperation("重置密码")
    //@RequiresPermissions("sys:user:resetPwd")
    public Result<SysUserDTO> resetPwd(@PathVariable("id") Long id) {
        SysUserDTO dtoDB = sysUserService.get(id);
        if (StringUtils.isEmpty(dtoDB)) {
            return new Result().error("用户不存在!");
        }
        sysUserService.resetPwd(id);
        sysUserService.clearLogin(id);// 清除指定用户登录状态
        return new Result();
    }

    @GetMapping("loadSelfInfo")
    @ApiOperation("获取当前登录者详细信息")
    public Result<SysUserDTO> loadSelfInfo() {
        UserDetail user = SecurityUser.getUser();
        Long id = user.getId();
        SysUserDTO data = sysUserService.get(id);
        //用户角色列表
        List<Long> roleIdList = sysRoleUserService.getRoleIdList(id);
        data.setRoleIdList(roleIdList);
        return new Result<SysUserDTO>().ok(data);
    }

    @PostMapping("updateSelf")
    @ApiOperation("修改个人信息")
    @LogOperation("修改个人信息")
    public Result updateSelf(@RequestBody SysUserDTO dto) {
        UserDetail user = SecurityUser.getUser();
        SysUserDTO dtoDB = sysUserService.get(user.getId());
        if (StringUtils.isEmpty(dtoDB)) {
            return new Result().error("当然用户不存在!");
        }
        dtoDB.setRealName(dto.getRealName());//真实姓名
        dtoDB.setGender(dto.getGender());//性别(0-男;1-女;2-保密)
        dtoDB.setMobile(dto.getMobile());//手机号码
        dtoDB.setEmail(dto.getEmail());//电子邮箱
        sysUserService.update(dtoDB, false);
        return new Result();
    }
}